const fs = require("fs");
const {faviconGenerator} = require('favicon-generator');


const path = require("path");//工具模块，处理文件路径的小工具
const JSZIP = require("jszip");
const zip = new JSZIP();


//读取目录及文件
function readDir(obj, nowPath) {
    let files = fs.readdirSync(nowPath);//读取目录中的所有文件及文件夹（同步操作）
      files.forEach(function (fileName, index) {//遍历检测目录中的文件
        console.log(fileName, index);//打印当前读取的文件名
         let fillPath = nowPath + "/" + fileName;
         let file = fs.statSync(fillPath);//获取一个文件的属性
         if (file.isDirectory()) {//如果是目录的话，继续查询
             let dirlist = zip.folder(fileName);//压缩对象中生成该目录
             readDir(dirlist, fillPath);//重新检索目录文件
         } else {
             obj.file(fileName, fs.readFileSync(fillPath));//压缩目录添加文件
         }
     });
 }


 //开始压缩文件
const startZip = async () =>  {
    var currPath = './';//文件的绝对路径 当前当前js所在的绝对路径
    var targetDir = path.join(currPath, "pwa-manifest");
    readDir(zip, targetDir);
    const content = await zip.generateAsync({//设置压缩格式，开始打包
        type: "nodebuffer",//nodejs用
        compression: "DEFLATE",//压缩算法
        compressionOptions: {//压缩级别
            level: 9
        }
    })

    fs.writeFileSync(currPath + "/pwa-manifest.zip", content, "utf-8");//将打包的内容写入 当前目录下的 result.zip中
    return ;
}


const createMoreImg = async (imgUrl) => {





    const icons = await faviconGenerator(`${imgUrl}`, [
        {
            width: 72,
            format: 'png',
        },
        {
            width: 96,
            format: 'png',
        },
        {
            width: 114,
            format: 'png',
        },
        {
            width: 128,
            format: 'png',
        },
        {
            width: 144,
            format: 'png',
        },
        {
            width: 152,
            format: 'png',
        },
        {
            width: 192,
            format: 'png',
        },
        {
            width: 384,
            format: 'png',
        },
        {
            width: 256,
            format: 'png',
        },
        {
            width: 512,
            format: 'png',
        }
    ])



    // imgs/icon-72x72.png
    // imgs/icon-96x96.png
    // imgs/icon-114x114.png
    // imgs/icon-128x128.png
    // imgs/icon-144x144.png
    // imgs/icon-152x152.png
    // imgs/icon-192x192.png
    // imgs/icon-384x384.png
    // imgs/icon-256x256.png
    // imgs/icon-512x512.png
    // fs.writeFileSync()
    // await fs.writeFile('./favicon1.png', favicons[0].buffer)
    // await fs.writeFile('./favicon2.png', favicons[1].buffer)
    
    // fs.writeFileSync(`imgs/icon-${}x72.png`)

    //icon-touch-icon-ipad-144.png
    //icon-touch-icon-iphone-114.png

    icons.forEach((item,key) => {

        fs.writeFileSync(`./pwa-manifest/imgs/icon-${item.width}x${item.width}.png`, icons[key].buffer)
    })
    

    fs.writeFileSync(`./pwa-manifest/imgs/icon-touch-icon-iphone-114.png`, icons[2].buffer)
    fs.writeFileSync(`./pwa-manifest/imgs/icon-touch-icon-ipad-144.png`, icons[4].buffer)
}


/**
 * 递归删除目录
 * @returns 
 */
const digui = (dir,arr) => {
    
    arr.forEach(element => {
        let isDir = fs.statSync(`${dir}/${element}`);
        if (isDir.isDirectory()) {
            let files = fs.readdirSync(`${dir}/${element}`);
                digui(`${dir}/${element}`,files)
        } else {
            fs.unlinkSync(`${dir}/${element}`) 
        }
    });
    fs.rmdirSync(dir)

}

/**
 * 创建目录pwa-manifest
 */
const createPwaManifestFolder = async () => {
    const FOLDER = './pwa-manifest';
    if (fs.existsSync(FOLDER)) {
        //递归调用删除
        let files = fs.readdirSync(FOLDER);
        digui(FOLDER, files);
    }
    fs.mkdirSync(FOLDER)
    return ;
}

/**
 * 生成文件 manifest.json
 * @param {string} tpl 
 * @returns 
 */
const createManiFestJson = (tpl) => {

    fs.writeFileSync("./pwa-manifest/manifest.json", tpl);
    return ;
}

/**
 * 生成图片的文件夹
 */
const createImgFolder = async () => {
    if (!fs.existsSync("./pwa-manifest/imgs")) {
        fs.mkdirSync("./pwa-manifest/imgs")
    }
    return ;
}

/**
 * 创建更多尺寸的图片
 * @param {string} imgUrl 
 */
const createMoreRuleImage = async (imgUrl) => {
    await createImgFolder();
    await createMoreImg(imgUrl);


}

/**
 * 生成index.html
 */
const createindexHtml = async (tpl) => {
    fs.writeFileSync("./pwa-manifest/index.html", tpl)

    return ;
}

const createStartPageHtml = (tpl) => {
    fs.writeFileSync("./pwa-manifest/startpage.html", tpl)

    return ;
}

const createFaviconIco = async (rule, imgUrl) => {
    console.log('空的');


    const icons = await faviconGenerator(`${imgUrl}`, [
        {
            width: rule,
            format: 'ico',
        }
    ]);

    console.log(icons);

    fs.writeFileSync(`./favicon.ico`, icons[0].buffer)
    return ;

}

module.exports = {
    //创建目录pwa-manifest
    createPwaManifestFolder,
    //写入manifest.json
    createManiFestJson,
    //生成更多尺寸图片
    createMoreRuleImage,
    //生成index.html
    createindexHtml,
    //生成startpage.html
    createStartPageHtml,
    //压缩 成.zip包
    startZip,
    //生成favicon.ico
    createFaviconIco
}